
import mapbox from 'mapbox-gl'

const blankStyle = {
  version: 8,
  name: 'BlankMap',
  sources: {},
  'sprite': 'http://localhost:8080/resources/mapbox/sprite',
  'glyphs': 'http://localhost:8080/resources/mapbox/{fontstack}/{range}.pbf',
  layers: []
}

const defaultOpts = {
  container: 'map',
  // style: 'mapbox://styles/mapbox/streets-v12',
  style: blankStyle,
  center: [108.99, 34.37],
  zoom: 3,
  // interactive: false,
  preserveDrawingBuffer: true,
  projection: 'mercator',
  // projection: {
  //   name: 'albers',
  //   center: [105, 0],
  //   parallels: [47, 25]
  // },
  trackResize: true,
  attributionControl: false
}

function initMap(options, loaded) {
  mapbox.accessToken = 'pk.eyJ1IjoiYW5uMiIsImEiOiJjamwzNDB0OTMwNmFtM2txZXczdXU3bXZ1In0.tKtwtN2PG1fNIxIHnhHjGA'

  const copyOpts = JSON.parse(JSON.stringify(defaultOpts))
  const opts = Object(copyOpts, options)
  opts.transformRequest = (url, resourceType) => { // 为数据源请求添加token
    console.log(url, resourceType)
    if (resourceType === 'Tile' && url.includes('egis')) {
      console.log(1, { 'Authorization': 'Bearer ' + process.env.VUE_APP_EGIS_TOKEN })
      return {
        url: url,
        headers: { 'Authorization': process.env.VUE_APP_EGIS_TOKEN }
      }
    }
  }

  const map = new mapbox.Map(opts)

  map.on('load', e => {
    loadEvent(map)

    loaded() // 回调
  })

  return map
}

function loadEvent(map) {
  const scale = new mapbox.ScaleControl({
    maxWidth: 80,
    unit: 'metric'
  })
  map.addControl(scale)

  // map.addControl(new mapbox.AttributionControl({
  //   customAttribution: '嘎嘎嘎'
  // }))
}
export { initMap }
